package com.test16_内部类;

import org.junit.Test;

/**
 * 匿名内部类
 */
public class YootkDemo_05 {

    @Test
    public void test1() {
        // 传统形式
        IMessage5 message = new MessageImpl5();
        System.out.println(message.echo("www.yootk.com"));
    }

    @Test
    public void test2() {
        {
            // 定义匿名内部类
            IMessage5 message = new IMessage5() {
                @Override
                public String echo(String msg) {
                    return "【沐言科技】" + msg;
                }
            };
            System.out.println(message.echo("www.yootk.com"));
        }
        {
            IMessage5 message = IMessage5.getDefaultMessage();
            System.out.println(message.echo("www.yootk.com"));
        }
    }

    @Test
    public void test3() {
        // 在抽象类中使用匿名内部类
        AbstractMessage5 message = new AbstractMessage5() {
            @Override
            public String echo(String msg) {
                return "【沐言科技】" + msg;
            }
        };
        System.out.println(message.echo("www.yootk.com"));
    }

    @Test
    public void test4() {
        // 在普通类中使用匿名内部类
        Book5 book = new Book5() {
            @Override
            public String toString() {
                return "【Book】书中自有黄金屋。";
            }
        };
        System.out.println(book);
    }
}

interface IMessage5 {
    public String echo(String msg);

    /**
     * 方法中定义匿名内部类
     */
    public static IMessage5 getDefaultMessage() {
        return new IMessage5() {
            @Override
            public String echo(String msg) {
                return "【沐言科技】" + msg;
            }
        };
    }
}

class MessageImpl5 implements IMessage5 {
    @Override
    public String echo(String msg) {
        return "【沐言科技】" + msg;
    }
}

abstract class AbstractMessage5 {
    public abstract String echo(String msg);
}

class Book5 {
    @Override
    public String toString() {
        return "【Book】书中自有颜如玉。";
    }
}
